package modellayer;

import java.util.*;
import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * Write a description of class PersonFileHandler here.
 * 
 * @author (Søren Kaae) 
 * @version (09.12.2014)
 */
public class VareFileHandler
{
    // instance variables - replace the example below with your own
    private String vareFileName;

    /**
     * Constructor for objects of class PersonFileHandler
     */
    public VareFileHandler(String vareFileName)
    {
        // initialise instance variables
        this.vareFileName = vareFileName;
    }

    public void saveToFile(ArrayList<Vare> varer) throws IOException
    {
        File destination = makeAbsoluteFilename(vareFileName);
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(destination));
        os.writeObject(varer);
        os.close();
    }

    public ArrayList<Vare> readFromFile() throws IOException, ClassNotFoundException
    {
        ArrayList<Vare> returnList = new ArrayList<Vare>();
        // Make sure the file can be found.
        URL resource = getClass().getResource(vareFileName);
        if(resource == null) {
            throw new FileNotFoundException(vareFileName);
        }
        try {
            File source = new File(resource.toURI());
            ObjectInputStream is = new ObjectInputStream(new FileInputStream(source));
            returnList = (ArrayList<Vare>)is.readObject();
            is.close();
        }
        catch(URISyntaxException e) {
            throw new IOException("Unable to make a valid filename for " + vareFileName);
        }
        return returnList;
    }

    private File makeAbsoluteFilename(String vareFileName) throws IOException
    {
        try {
            File file = new File(vareFileName);
            if(!file.isAbsolute()) {
                file = new File(getProjectFolder(), vareFileName);
            }
            return file;
        }
        catch(URISyntaxException e) {
            throw new IOException("Unable to make a valid filename for " + vareFileName);
        }
    }

    private File getProjectFolder() throws URISyntaxException
    {
        String file = getClass().getName();
        String myClassFile = file.substring(11) + ".class";        
        URL url = getClass().getResource(myClassFile);
        return new File(url.toURI()).getParentFile();
    }

}

